# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: P_λ.py
  @time: 2022/3/18 10:13
  @desc:光谱扫描？？
"""
import time
from utils.save_setting_2_ini import save_ini_info
from matplotlib import pyplot as plt
from scipy.signal import savgol_filter
from ATS.application.LASER_App.N7744C_App import N7744C_App
from ATS.application.LASER_App.L8164B_App import L8164B_App
from ATS.application.LASER_App.N7786C_App import N7786C_App
from ATS.switchdriver.LightSwitchDriver import LightSwitchDriver
from ATS.datamanager import data_transfer_station as DataTransferStation
from utils.read_ini_2_dict import get_option_value, get_refrence_data
from utils.get_wave_power_util import get_wave_power_value
import csv
from collections import namedtuple
from gui import constant
from utils.log_util import loggings


def spectral_scan(para):
    result_data = namedtuple("result_data", "subdie,test_item,curve_type,test_result")
    n7744c_app = N7744C_App(para.n7744_setting["title"])
    l8164b_app = L8164B_App(para.l8164_setting["title"])
    light_inst = LightSwitchDriver.instance()

    if light_inst.is_connected:
        light_inst.set_all_switch("01", "05")
        time.sleep(1)
        loggings.info("spectral_scan " + str(light_inst.query_switch()))
    else:
        light_inst.connect()
    n7744c_app.set_logging_state("STOP")
    x_data = para.l8164_setting['wave_length']
    points = len(x_data)
    l8164b_app.set_power_unit()
    l8164b_app.set_power_value(para.l8164_setting["power_value"])
    time.sleep(4)
    p_in = l8164b_app.fetch_input_power()
    l8164b_app.set_sweep_mode()
    l8164b_app.query_sweep_pmax(para.l8164_setting['wave_length'][0], para.l8164_setting['wave_length'][-1])
    l8164b_app.set_repeat_mode()
    l8164b_app.set_wave_sweep_speed()
    l8164b_app.set_start_stop_step_wave(para.l8164_setting['wave_length'][0], para.l8164_setting['wave_length'][-1],
                                        float(para.l8164_setting['wave_length'][1]) - float(
                                            para.l8164_setting['wave_length'][0]))
    l8164b_app.trigger_config()
    l8164b_app.trigger_output()
    l8164b_app.trigger_input()
    l8164b_app.output_on()
    l8164b_app.set_wave_sweep_state()
    # n7744c_app.reset()
    n7744c_app.set_power_unit()
    n7744c_app.set_power_range(para.n7744_setting["power_range"])
    n7744c_app.set_auto_gain()
    n7744c_app.set_power_atim(para.n7744_setting["atim"])
    n7744c_app.trigger_input_mode()
    n7744c_app.set_power_wave_length()
    n7744c_app.set_logging_points(points)
    n7744c_app.set_logging_state()
    n7744c_app.tigger_status()
    while True:
        state = n7744c_app.get_func_state()
        if state == "LOGGING_STABILITY,COMPLETE":
            y_data = n7744c_app.get_func_res()
            break
    y_data = [float(i) for i in y_data]
    l8164b_app.stop_sweep()

    wave_power_tuple = get_refrence_data()
    for wave_index in range(len(x_data)):
        y_data[wave_index] = float(p_in) - y_data[wave_index] - get_wave_power_value(x_data[wave_index],
                                                                                     wave_power_tuple)
    min_power = min(y_data)
    min_index = y_data.index(min_power)
    wave = x_data[min_index]
    loss_gc_list = [float(i) / 2 for i in y_data]
    try:
        DataTransferStation.get_DTS().postarraydata("test",
                                                    result_data(para.subdie, para.test_item, "line", (x_data, y_data)))
        save_ini_info(constant.REMEMBER_VALUE, "remember_value", "wave_length", str(wave))
        save_ini_info(constant.REMEMBER_VALUE, "remember_value", "power_value", str(min_power))
        save_ini_info(constant.REFRENCE_FILE, "loss_gc_data", "loss_gc", str(loss_gc_list))
        save_ini_info(constant.REFRENCE_FILE, "loss_gc_data", "wave_data", str(x_data))
    except Exception as e:
        loggings.error("spectral_scan " + str(e))


def plot_curve1(x_data, y_data):
    plt.plot(x_data, y_data, "b")
    plt.xlabel("WaveLength")
    plt.ylabel("Value")
    plt.grid(True)
    plt.show()


# 平滑曲线
def savgol(x_data, y_data):
    plt.plot(x_data, y_data, "k")
    y_smooth = savgol_filter(y_data, 201, 3, mode="nearest")
    plt.plot(x_data, y_smooth, "b")
    plt.xlabel("WaveLength")
    plt.ylabel("Value")
    plt.grid(True)
    plt.show()


def saveData2CSV(file_path, header, data_content):
    with open(file_path, 'w', newline='', encoding="utf_8_sig") as csvfile:
        writer = csv.writer(csvfile)
        # 写入表格的标题
        writer.writerow(header)
        # 循环写入表格的内容
        for i in range(len(data_content[0][0])):
            row_data = []
            for j in range(len(data_content[0])):
                row_data.append(data_content[0][j][i])
            writer.writerow(row_data)


spectral_scan(locals()["para"])
